﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Albon.Model;
using System.Web;
using System.IO;
using System.Net;
namespace BLL
{
    public class InvoiceBLL
    {

        private readonly DAL.InvoiceDAL invoicedal = new DAL.InvoiceDAL();
        private readonly PayMethodBLL paymethodbll = new PayMethodBLL();
        private readonly PayMentBLL paymentbll = new PayMentBLL();

        /// <summary>
        /// 获取订单的应付款数
        /// </summary>
        public decimal getTotalMoney(string invoiceNo)
        {
            DataTable dt=invoicedal.getInvoice(invoiceNo);
            return decimal.Parse(dt.Rows[0]["totalMoney"].ToString());
        }

        /// <summary>
        /// 添加,订单完成时自动添加，totalMoney初始值为0.修改，修改订单的同时要修改invoiceTotal，
        /// </summary>
        public bool alterInvoice(Invoice invoice)
        {
            return invoicedal.alterInvoice(invoice);
        }

        /// <summary>
        /// 计算应付款，发票标记为“已查看”
        /// </summary>
        public bool totalMoney(Invoice invoice)
        {
            return invoicedal.totalMoney(invoice);
        }

        /// <summary>
        /// 根据invoiceMoney,totalMoney,payMent和payMethod判断发票的状态 
        /// 四个状态完成付款（finish）,未计算/系统生成（untotaled），已计算/已确认（totaled）,已改变（changed）
        /// </summary>
        public string getStatus(string invoiceNo)
        {
            string status = "";
            if (invoiceNo != "")
            {

                DataTable dt = invoicedal.getInvoice(invoiceNo);
                decimal invoiceTotal = decimal.Parse(dt.Rows[0]["invoiceTotal"].ToString());
                decimal totalMoney = decimal.Parse(dt.Rows[0]["totalMoney"].ToString());

                decimal percentage = paymethodbll.getPercentage(dt.Rows[0]["payMethod"].ToString());

                if (totalMoney == 0)
                {
                    status = "untotaled";
                }
                else if (paymentbll.Balance(invoiceNo) < 0)
                {
                    status = "totaled";
                } 
                else
                {
                    status = "finished";
                }
            }
            else
            {
                status = "no";
            }
            return status;
            
        }
        /// <summary>
        /// 生成invoiceID（订单时间（yyMMhh）+当天订单的个数）
        /// </summary>
        public  int getInvoiceNo(string orderid)
        {
            OrderBLL orderbll = new OrderBLL();
            DataTable dt = orderbll.getOrderByID(orderid);
            DateTime createDate=DateTime.Parse(dt.Rows[0]["createDate"].ToString());
            string date = createDate.ToString("yyMMdd");
            DAL.OrderDAL orderdal = new DAL.OrderDAL();
            //当天的第几个订单（最少三位数）
            DataTable count=orderdal.getOrder("createDate>'"+date+"' and createDate<='"+createDate.ToString()+"'");
            string seq=count.Rows.Count.ToString().PadLeft(3, '0');
            return int.Parse(date + seq);
        }

        //根据InvoiceNo获取invoice信息
        public DataTable getInvoiceByNo(string invoiceNo)
        {
            return invoicedal.getInvoice(invoiceNo);
        }

        //超出尺寸收费
        public DataTable overSizeCharge(string orderid)
        {
            DataTable oversize = new DataTable();
            ItemSizeBLL itemsizebll = new ItemSizeBLL();
            OrderItemBLL orderitembll = new OrderItemBLL();
            string itemname = "";
            string stylename="";
            foreach (DataRow dr in orderitembll.getItemByOrderID(orderid).Rows)
            {
                itemname = dr["itemName"].ToString();
                foreach (string styleid in dr["styleList"].ToString().Split(','))
                {
                    DataTable dt=itemsizebll.getMaxOverSize(dr["ID"].ToString(), styleid);
                    foreach(DataRow drSize in dt.Rows)
                    { 
                        StyleBLL stylebll = new StyleBLL();
                        stylename= stylebll.getStyleName(styleid);
                        bool fit = bool.Parse(dr["FT"].ToString());
                        double percentage = 0;
                        double size = double.Parse(drSize["bodySize"].ToString());
                        if (size > 58)
                        {
                            percentage = 0.3;
                        }
                        else if (size < 58 && size > 53)
                        {
                            percentage = 0.2;
                        }
                        else if (size < 53 && size > 48)
                        {
                            percentage = 0.1;
                        }
                        if (size > 48)
                        {
                            dt.Columns.Add("styleName", typeof(string));
                            drSize["styleName"] = itemname + "-" + stylename;
                            dt.Columns.Add("qty", typeof(int));
                            int qty=int.Parse(dr["quantity"].ToString());
                            drSize["qty"] = qty;
                            dt.Columns.Add("percentage", typeof(double));
                            drSize["percentage"] = percentage;
                            dt.Columns.Add("itemPrice", typeof(float));
                            ItemPriceBLL itempricebll=new ItemPriceBLL();
                            DataTable itemPrice= itempricebll.getOrderItemPrice(orderid, styleid);
                            float FSPrice = 0;
                            float AFPrice = 0;
                            if (itemPrice.Rows.Count > 0)
                            {
                                FSPrice = float.Parse(itemPrice.Rows[0]["FSPrice"].ToString());
                                AFPrice = float.Parse(itemPrice.Rows[0]["AFPrice"].ToString());
                            }
                            float price=fit ? FSPrice + AFPrice : FSPrice;
                            drSize["itemPrice"] = price;
                            dt.Columns.Add("total", typeof(float));
                            drSize["total"] = qty * price * percentage;
                            oversize.Merge(dt);
                        }
                    }
                }
            }
            return oversize;
        }
        /// <summary>
        /// get order cloth charge
        /// </summary>
        public DataTable clothCharge(string orderid)
        {
            ItemClothBLL itemclothbll = new ItemClothBLL();
            DataTable dt=itemclothbll.getItemClothByOrderID(orderid);
            dt.Columns.Add("total", typeof(float));
            foreach (DataRow dr in dt.Rows)
            {
                //计算布料尺寸
                float total = float.Parse(dr["clothSize"].ToString()) * float.Parse(dr["quantity"].ToString()) * float.Parse(dr["clothPrice"].ToString());
                UnitBLL unitbll=new UnitBLL();
                float rate = unitbll.getChangeRate(dr["unitID"].ToString());
                dr["total"] = total/rate;
            }
            return dt;
        }
        /// <summary>
        /// get order item charge
        /// </summary>
        public DataTable itemCharge(string orderid)
        {
            ItemPriceBLL itempricebll=new ItemPriceBLL();
            DataTable dt = itempricebll.getOrderItemPrice(orderid);
            dt.Columns.Add("total", typeof(float));
            foreach (DataRow dr in dt.Rows)
            { 
                float price=float.Parse(dr["FSPrice"].ToString());
                if(bool.Parse(dr["FT"].ToString()))
                {
                    price+=float.Parse(dr["AFPrice"].ToString());
                       
                }
                dr["total"] = float.Parse(dr["quantity"].ToString()) * price;
            }
            return dt;
        }

        /// <summary>
        /// get Ship Charge
        /// </summary>
        public DataTable shipCharge(string orderid)
        {
            ShipBLL shipbll = new ShipBLL();
            DataTable dt= shipbll.getShipChargeView(orderid);
            float totalweight = 0;
            dt.Columns.Add("total", typeof(float));
            foreach (DataRow dr in dt.Rows)
            {
                bool fit = bool.Parse(dr["FT"].ToString());
                totalweight = float.Parse(dr["quantity"].ToString()) * (fit ? 2 : 1) * float.Parse(dr["weight"].ToString());
                dr["total"] = totalweight;
            }
            return dt;
        }
        /// <summary>
        /// get Extra Charge
        /// </summary>
        /// <param name="invoiceNo"></param>
        public DataTable getExtras(string invoiceNo)
        {
            return invoicedal.getExtras(invoiceNo);
        }
        /// <summary>
        /// 根据试身的数量和衣服总重计算运费总数
        /// </summary>
        public float getTotalShipCharge(string orderid,int fitNum, float total)
        {
            OrderBLL orderbll = new OrderBLL();
            DataTable dtShipPrice= orderbll.getCountry(orderid);
            float basePrice=float.Parse(dtShipPrice.Rows[0]["baseShipPrice"].ToString());
            float addPrice = float.Parse(dtShipPrice.Rows[0]["addShipPrice"].ToString());
            //运费计算以（500g）斤为单位
            float jin = total * 2;
            float b = (fitNum==0)?1:fitNum+1;
            float add = jin - b;
            //最终计算方法（有待确认）
            return b * basePrice + add * addPrice;
        }


        /// <summary>
        /// Add a Extra Charge
        /// </summary>
        /// <param name="extra"></param>
        public void addExtraCharge(ExtraCharge extra)
        {
            invoicedal.addExtraCharge(extra);
        }

        /// <summary>
        /// remove a Extra Charge
        /// </summary>
        /// <param name="id"></param>
        public void removeExtraCharge(string id)
        {
            invoicedal.deleteExtraCharge(id);
        }


        /// <summary>
        /// 将aspx页保存为HTML静态页
        /// </summary>
        public void saveAsStaticFile(string url, string username, string invoiceno)
        {
            //对于不想在静态页内可用的元素，使用标记，在此处替换为 
            string content = GetContent(url).Replace("title=\"disable\"", "disabled=\"disabled\"");
            string directory = HttpContext.Current.Server.MapPath("/StaticPage/Invoice/") + username;
            string filepath = directory + "/" + invoiceno + ".html";
            Directory.CreateDirectory(directory);
            using (StreamWriter sw = new StreamWriter(filepath))
            {
                sw.Write(content);
            }
        }

        /// <summary>
        /// 根据URL获取页面内容
        /// </summary>
        public string GetContent(string url)
        {
            //变量定义 
            string respstr;
            WebRequest myWebRequest = WebRequest.Create(url);
            myWebRequest.PreAuthenticate = false;
            // NetworkCredential networkCredential=new NetworkCredential( username , password , domain ); 
            // myWebRequest.Credentials=networkCredential; 
            // Assign the response object of 'WebRequest' to a 'WebResponse' variable. 
            WebResponse myWebResponse = myWebRequest.GetResponse();
            Stream stream = myWebResponse.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.Default);
            //以字符串形式读取数据流 
            respstr = sr.ReadToEnd();
            sr.Close();
            return respstr;
        }
    }
}